<template>
  <div class="split-bar" @touchstart="onTouchStart" @mousedown="onMousedown">
    <div class="trapezoid">
      <img src="@/assets/xiala.png" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps({
  layout: {
    type: String,
    values: ['horizontal', 'vertical'] as const,
    default: 'vertical'
  }
})

const startPos = ref<[x: number, y: number] | null>(null)
const isHorizontal = computed(() => props.layout === 'horizontal')

const Emit = defineEmits<{
  (e: 'moveStart'): void
  (e: 'moveEnd'): void
  (e: 'moving', data: number): void
}>()
const onTouchStart = (e: TouchEvent) => {
  if (e.touches.length === 1) {
    e.preventDefault()
    const touch = e.touches[0]
    startPos.value = [touch.pageX, touch.pageY]
    Emit('moveStart')
    window.addEventListener('touchend', onTouchEnd)
    window.addEventListener('touchmove', onTouchMove, { passive: false })
  }
}

const onMousedown = (e: MouseEvent) => {
  startPos.value = [e.pageX, e.pageY]
  Emit('moveStart')
  window.addEventListener('mouseup', onMouseUp)
  window.addEventListener('mousemove', onMouseMove)
}

const onTouchEnd = () => {
  startPos.value = null
  window.removeEventListener('touchend', onTouchEnd)
  window.removeEventListener('touchmove', onTouchMove)
  Emit('moveEnd')
}

const onTouchMove = (e: TouchEvent) => {
  if (e.touches.length === 1) {
    e.preventDefault()
    const touch = e.touches[0]
    const offsetX = touch.pageX - startPos.value![0]
    const offsetY = touch.pageY - startPos.value![1]
    const offset = isHorizontal.value ? offsetX : offsetY
    Emit('moving', offset)
  }
}

// End dragging
const onMouseUp = () => {
  startPos.value = null
  window.removeEventListener('mouseup', onMouseUp)
  window.removeEventListener('mousemove', onMouseMove)
  Emit('moveEnd')
}

// During dragging
const onMouseMove = (e: MouseEvent) => {
  const { pageX, pageY } = e
  const offsetX = pageX - startPos.value![0]
  const offsetY = pageY - startPos.value![1]
  const offset = isHorizontal.value ? offsetX : offsetY
  Emit('moving', offset)
}
</script>

<style lang="scss" scoped>
.split-bar {
  width: 100%;
  position: absolute;
  top: -42px;
  left: 0;
  background-color: transparent;
}

.trapezoid {
  width: 111px;
  margin: 0 auto;
  img {
    width: 100%;
  }
}
</style>
